package com.dnjn.happiness.system.controller;

import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.model.PositionLadderVO;
import com.dnjn.happiness.common.core.utils.bean.BeanUtils;
import com.dnjn.happiness.common.core.utils.poi.ExcelUtil;
import com.dnjn.happiness.common.core.web.page.TableDataInfo;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.security.annotation.InnerAuth;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import com.dnjn.happiness.system.api.domain.SysDept;
import com.dnjn.happiness.system.api.domain.SysRole;
import com.dnjn.happiness.system.api.domain.SysUser;
import com.dnjn.happiness.system.api.model.LoginUser;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.system.domain.PositionLadder;
import com.dnjn.happiness.system.model.SysUserDTO;
import com.dnjn.happiness.system.service.*;
import com.github.pagehelper.Page;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author happy
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {
    public static final String PERM_SYSTEM_USER_SENSITIVE = "system:user:sensitive";
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysPermissionService permissionService;

    @Autowired
    private ISysConfigService configService;


    @InnerAuth
    @GetMapping("/getUserListAll")
    public R<List<SysUser>> getUserListAll(){
        return R.ok(userService.getUserListAll());
    }


    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/getUserByUnId/{id}")
    public R<SysUser> getUserByUnId(@PathVariable("id") String id)
    {
        return R.ok(userService.getUserByUnId(id));
    }

    @InnerAuth
    @GetMapping("/selectUserAndScore/{userId}")
    public R<SysUser> selectUserAndScore(@PathVariable Long userId){
        return R.ok(userService.selectUserAndScore(userId));
    };


    /**
     * 根据领导id 查询所有直接下级
     */
    @InnerAuth
    @GetMapping("/selectUsersByLeaderId/{leaderId}")
    public R<List<SysUser>> selectUsersByLeaderId(@PathVariable Long leaderId){
        return R.ok(userService.selectUsersByLeaderId(leaderId));
    }


    /**
     * 根据部门Id查询当前部门下的用户数量
     */
    @InnerAuth
    @PostMapping("/queryUserListByDeptId")
    public R<List<SysUser>> queryUserListByDeptId(@RequestParam(required = false) Long currtDeptId,@RequestParam(required = false) String nickName){
        return R.ok(userService.queryUserListByDeptId(currtDeptId,nickName));
    }

    /**
     * 根据部门Id查询当前部门下的用户数量
     */
    @InnerAuth
    @GetMapping("/selectUserCount/{deptId}")
    public R<Integer> selectUserCount(@PathVariable Long deptId){
        return R.ok(userService.selectUserCount(deptId));
    }

    @InnerAuth
    @GetMapping("/queryPositionListByDeptId/{deptId}")
    public R<List<PositionLadderVO>> queryPositionListByDeptId(@PathVariable Long deptId){
        List<PositionLadder> list = userService.queryPositionListByDeptId(deptId);
        List<PositionLadderVO> voList = new ArrayList<>();
        list.forEach(item->{
            PositionLadderVO vo = new PositionLadderVO();
            BeanUtils.copyBeanProp(vo,item);
            voList.add(vo);
        });
        return R.ok(voList);
    }

    @InnerAuth
    @PostMapping("/getUsersByDeptIdList")
    public R<Long> getUsersByDeptIdList(@RequestBody List<Long> deptIdList){
        return R.ok(userService.getUsersByDeptIdList(deptIdList));
    }

    @InnerAuth
    @PostMapping("/getCommunicationCount/{num}")
    public R<Long> getCommunicationCount(@PathVariable Integer num,@RequestBody List<Long> deptIdList){
        return R.ok(userService.getCommunicationCount(deptIdList,num));
    }



    /**
     * 注册用户信息
     */
    @InnerAuth
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody SysUser sysUser)
    {
        String username = sysUser.getUserName();
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
        {
            return R.fail("当前系统没有开启注册功能！");
        }
        if (!userService.checkUserNameUnique(sysUser))
        {
            return R.fail("保存用户'" + username + "'失败，注册账号已存在");
        }
        return R.ok(userService.registerUser(sysUser));
    }

    /**
     * 根据工号姓名查询用户信息
     */
    @InnerAuth
    @GetMapping("/selectUserByEmpnoAndUserName/{empno}/{username}")
    public R<LoginUser> selectUserByEmpnoAndUserName(@PathVariable("empno") String empno,@PathVariable("username") String username)
    {
        SysUser sysUser = userService.selectUserByEmpnoAndUserName(empno,username);
        if (StringUtils.isNull(sysUser))
        {
            return R.fail("用户名或工号或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username)
    {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser))
        {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    @InnerAuth
    @GetMapping("/selectUserById/{userId}")
    public R<SysUser> selectUserById(@PathVariable Long userId){
        return R.ok(userService.selectUserById(userId));
    };

    @InnerAuth
    @GetMapping("/selectUserInfo/{userId}")
    public R<SysUser> selectUserInfo(@PathVariable Long userId){
        return R.ok(userService.selectUserInfo(userId));
    };

    @InnerAuth
    @PostMapping("/selectUserList")
    public R<List<SysUser>> selectUserList(@RequestBody SysUser sysUser){
        return R.ok(userService.selectUserList(sysUser));
    };

    @InnerAuth
    @PostMapping("/getUsersByPostId")
    public R<List<SysUser>> getUsersByPostId(@RequestBody Map<String, Object> map){
        return R.ok(userService.getUsersByPostId(map));
    };

    @InnerAuth
    @PostMapping("/getUsersByPosition")
    public R<List<SysUser>> getUsersByPosition(@RequestBody Map<String, Object> map){
        return R.ok(userService.getUsersByPosition(map));
    };

    /**
     * 根据部门id获取部门下得所有用户id集合
     * @param userId
     * @return
     */
    @InnerAuth
    @GetMapping("/selectUserListByDeptIdList/{userId}")
    public R<List<Long>> selectUserListByDeptIdList(@PathVariable Long userId){
        return R.ok(userService.selectUserListByDeptIdList(userId));
    };





    /**
     * 获取全部用户列表
     */
    @RequiresPermissions("system:user:query")
    @PostMapping("/getUserListAll")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getUserListAll(@RequestParam String nickName) {
        List<SysUser> list = userService.getUserListAllLimit(nickName);
        return AjaxResult.success(iconvSysUserDTO(list));
    }

    /**
     * 获取用户列表
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);

        TableDataInfo dataInfo = getDataTable(iconvSysUserDTO(list));
        return dataInfo;
    }


    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
//        List<SysUserDTO> rv = iconvSysUserDTO(list);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }



    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }



    /**
     * 根据用户编号获取详细信息
     */

    @RequiresPermissions("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        Long currentUserId = SecurityUtils.getUserId();
        List<Long> roleList = roleService.selectRoleListByUserId(currentUserId);
        ajax.put("roles", SysUser.isAdmin(SecurityUtils.getUserId(), roleList) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, iconvSysUserDTO(sysUser));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }


    /**
     * 脱敏过滤补救
     */
    //@RequiresPermissions("system:user:sensitive")
    @GetMapping(value = "/getSensitiveInfo/{userId}")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getSensitiveInfo(@PathVariable(value = "userId") Long userId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        AjaxResult ajax = AjaxResult.success();

        if (loginUser.getUserid().equals(userId) || loginUser.getPermissions().contains(PERM_SYSTEM_USER_SENSITIVE)) {
            userService.checkUserDataScope(userId);
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);//!
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 修改用户时，查看当前用户是否具有修改权限
     */
    @RequiresPermissions("system:user:query")
    @GetMapping(value = "/getIsPermission/{userId}")
    public AjaxResult getIsPermission(@PathVariable(value = "userId") Long userId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        AjaxResult ajax = AjaxResult.success();
        Boolean flag = false;
        List<Long> roleList = roleService.selectRoleListByUserId(SecurityUtils.getUserId());
        if (loginUser.getUserid().equals(userId) || loginUser.getPermissions().contains(PERM_SYSTEM_USER_SENSITIVE) || SysUser.isAdmin(SecurityUtils.getUserId(), roleList)) {
            userService.checkUserDataScope(userId);
            flag = true;
        }
        ajax.put("flag", flag);
        return ajax;
    }


    /**
     * 新增用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }


    /**
     * 修改用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {

        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        if ("1".equals(user.getStatus())) {
            if (userService.checkUserIsManager(user.getUserId())) {
                return error("当前选中用户存在人员架构绑定.请先解除该人的绑定关系");
            }
        }
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
            return error("当前用户不能删除");
        }
        for (Long userId : userIds) {
            if (userService.checkUserIsManager(userId)) {
                return error("当前选中用户存在人员架构绑定.请先解除该人的绑定关系");
            }
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {

        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        if ("1".equals(user.getStatus())) {
            if (userService.checkUserIsManager(user.getUserId())) {
                return error("当前选中用户存在人员架构绑定.请先解除该人的绑定关系");
            }
        }
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @RequiresPermissions("system:user:query")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        Long currentUserId = SecurityUtils.getUserId();
        List<Long> roleList = roleService.selectRoleListByUserId(currentUserId);
        ajax.put("roles", SysUser.isAdmin(SecurityUtils.getUserId(), roleList) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }
    /**
     * 获取部门树列表
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/deptTreeAdmin")
    public AjaxResult deptTreeAdmin(SysDept dept) {
        dept.setStatus("0");
        return success(deptService.selectDeptTreeList(dept));
    }

    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        dept.setStatus("0");
        return success(deptService.selectDeptTreeList(dept));
    }


    /**
     * 获取当前的部门下的用户
     *
     * @Param: deptId
     * @Param: nickName 模糊搜索名称
     * 搜索名称需要携带部门Id过来
     */
//    @RequiresPermissions("system:user:query")
    @Operation(summary = "获取当前的部门下的用户")
    @GetMapping("/getUserListByDeptIdAdmin")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getUserListByDeptIdAdmin(SysUser sysUser) {



        List<SysUser> userList = userService.getUserListByDeptId1(sysUser);
        return success(iconvSysUserDTO(userList));
    }

    @Operation(summary = "获取当前的部门下的用户")
    @GetMapping("/getUserListByDeptId")
//    @RequiresPermissions("system:user:query")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getUserListByDeptId(SysUser sysUser) {

        if (StringUtils.isNotEmpty(sysUser.getNickName())) {//如果搜索名称，控制查询范围在当前用户的deptId下面
            Long userId = SecurityUtils.getUserId();
            sysUser.setDeptId(userService.selectUserById(userId).getDeptId());
        }
        if (Objects.isNull(sysUser.getDeptId())) {
            Long userId = SecurityUtils.getUserId();
            sysUser.setDeptId(userService.selectUserById(userId).getDeptId());
        }


        List<SysUser> userList = userService.getUserListByDeptId(sysUser);
        return success(userList);
    }

    /**
     * 修改用户昵称，手机号,个人履历,婚姻信息,子女情况
     */
    @Operation(summary = "修改用户昵称，手机号,个人履历,婚姻信息,子女情况")
    @PostMapping("/updateUser")
    @RequiresPermissions("system:user:edit")
    public AjaxResult updateUser(@RequestBody SysUser user) {
        if (StringUtils.isNotEmpty(user.getResumeurl())) {
            validLinkedUrl(user.getResumeurl());
        }
        if (ObjectUtils.isEmpty(user.getUserId())) {
            user.setUserId(SecurityUtils.getUserId());
        }
        if (StringUtils.isNotEmpty(user.getPhonenumber())) {
            if (!userService.checkPhoneUnique(user)) {
                return error("手机号" + user.getPhonenumber() + "已经存在");
            }
        }
        userService.updateWxUser(user);
        return AjaxResult.success();
    }

    /**
     * 修改用户昵称，手机号,个人履历,婚姻信息,子女情况
     */
    @Operation(summary = "修改用户昵称，手机号,个人履历,婚姻信息,子女情况")
    @PostMapping("/updateWxUser")
    public AjaxResult updateWxUser(@RequestBody SysUser user) {
        if (ObjectUtils.isEmpty(user.getUserId())) {
            user.setUserId(SecurityUtils.getUserId());
        }
        if (StringUtils.isNotEmpty(user.getResumeurl())) {
            validLinkedUrl(user.getResumeurl());
        }
        if (StringUtils.isNotEmpty(user.getPhonenumber())) {
            if (!userService.checkPhoneUnique(user)) {
                return error("手机号" + user.getPhonenumber() + "已经存在");
            }
        }
        userService.updateWxUser(user);
        return AjaxResult.success();
    }



    @Operation(summary = "WX根据userId查询家庭信息和个人履历地址")
    @GetMapping("/getFamilyAndResumeurlByUserId/{userId}")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getFamilyAndResumeurlByUserId(@PathVariable Long userId) {
        Assert.notNull(userId, "用户ID不能为空");
        SysUser sysUser = userService.getFamilyInfoByUserId(userId);
        return AjaxResult.success(sysUser);
    }


    /**
     * 删除用户个人履历
     */
    @Operation(summary = "删除用户个人履历")
    @GetMapping("/deleteResumeById/{userId}")
    @RequiresPermissions("@ss.hasPermi('system:user:remove')")
    public AjaxResult deleteResumeById(@PathVariable Long userId) {
        userService.deleteResumeById(userId);
        return AjaxResult.success();
    }

    /**
     * 小程序上传用户专属头像
     */
    @Operation(summary = "小程序上传用户专属头像")
    @PutMapping("/setExclusiveAvatar")
    public AjaxResult setExclusiveAvatar(@RequestBody SysUser user) {
        String exclusiveAvatar = user.getExclusiveAvatar();
        Assert.notNull(exclusiveAvatar, "用户专属头像地址不能为空！");
        validLinkedUrl(user.getExclusiveAvatar());
        if (StringUtils.isNotEmpty(exclusiveAvatar)) {
            Long userId = SecurityUtils.getUserId();
            user.setUserId(userId);
            user.setExclusiveAvatarStatus("0");
            int i = userService.updateWxUser(user);
            if (i > 0) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error();
            }
        }
        return AjaxResult.error();
    }

    private List<SysUserDTO> iconvSysUserDTO(List<SysUser> list) {
        if (list instanceof Page) {
            Page page = (Page) list;
            Page<SysUserDTO> page1 = new Page<SysUserDTO>(page.getPageNum(), page.getPageSize());
            page1.setTotal(page.getTotal());
            page.forEach(el -> {
                SysUserDTO dto = SysUserDTO.iconv((SysUser) el);
                page1.add(dto);
            });
            return page1;
        }
        return list.stream().map(SysUserDTO::iconv).collect(Collectors.toList());
    }


    private SysUserDTO iconvSysUserDTO(SysUser sysUser) {
        return SysUserDTO.iconv(sysUser);
    }


    /**
     * 查询去指派 -》 执行列表
     * 查询 当前登录用户Id，被沟通人用户id
     *
     * @param :currentUserId 当前登录用户id
     * @param :userId        被沟通人id
     */
    @GetMapping("/queryUserListByUserId/{userId}")
    @RequiresPermissions("biz:communicate:query")
    public AjaxResult queryUserListByUserId(@PathVariable Long userId) {
        SysDept currentDept = deptService.selectSuperDeptList(SecurityUtils.getUserId());
        SysDept dept = deptService.selectSuperDeptList(userId);
        List<SysUser> userList = new ArrayList<>();
        Set<Long> userIds = new HashSet<>();
        if (null != currentDept && null != dept) {
            List<String> currentAncestors = Arrays.stream(currentDept.getAncestors().split(",")).collect(Collectors.toList());
            currentAncestors.add(currentDept.getDeptId().toString());
            List<String> ancestors = Arrays.stream(dept.getAncestors().split(",")).collect(Collectors.toList());
            ancestors.add(dept.getDeptId().toString());
            for (String deptId : ancestors) {
                if (!currentAncestors.contains(deptId)) {
                    SysDept sysDept = deptService.selectDeptById(Long.parseLong(deptId));
                    if (!ObjectUtils.isEmpty(sysDept.getLeaderId()) && !userId.equals(sysDept.getLeaderId())) {
                        userIds.add(sysDept.getLeaderId());

                    }
                }
            }
            if (userIds.size() > 0) {
                for (Long id : userIds) {
                    SysUser sysUser = userService.selectUserInfo(id);
                    if (null != sysUser) {

                        userList.add(sysUser);
                    }
                }
            }


            return AjaxResult.success(userList);
        }

        return AjaxResult.success(userList);

    }

}
